package net.chenlin.dp.modules.business.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import net.chenlin.dp.common.entity.R;
import net.chenlin.dp.common.utils.CommonUtils;
import net.chenlin.dp.modules.business.dao.DeviceRegisterMapper;
import net.chenlin.dp.modules.business.entity.dto.ExceFileDto;
import net.chenlin.dp.modules.business.entity.po.ExceFilePo;
import net.chenlin.dp.modules.business.entity.vo.file.SysFile;
import net.chenlin.dp.modules.business.service.DataImportService;
import net.chenlin.dp.modules.business.service.MinioSysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * @author Yangsm
 * @ClassName: FileUploadController
 * @Description: TODO
 * @date 2023年05月14日 17:25
 */
@Slf4j
@RestController
@RequestMapping("/file")
@Api(tags = "文件上传下载")
public class SysFileController {

    @Autowired
    private MinioSysFileService sysFileService;

    @Autowired
    private DataImportService dataImportService;

    @Autowired
    private DeviceRegisterMapper deviceRegisterMapper;

    /**
     * 文件上传请求
     */
    @PostMapping("/uploadFile")
    public R upload(@RequestParam("file") MultipartFile file, @RequestParam("districtId") Long districtId) {
        if(null == file){
            return R.error("未上传文件");
        }
        if(null == districtId){
            return R.error("台区主键ID为空");
        }
        try {
            // 上传并返回访问地址
            //MultipartFile file = exceFileDto.getFile();
            String url = sysFileService.uploadExcelFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(file.getOriginalFilename());
            sysFile.setUrl(url);
            sysFile.setAttachmentSize(file.getSize());
            //String fileName = sysFile.getName();
            //sysFile.setAttachmentSuffix(fileName.substring(fileName.lastIndexOf(".")));
            //批量导入案例
            ExceFilePo filePo = dataImportService.importExcelImportData(file);
            filePo.setDistrictId(districtId);
            filePo.setFileUrl(url);
            deviceRegisterMapper.insertExcelImportInfo(filePo);
            return CommonUtils.msg(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.error(e.getMessage());
        }
    }
}
